#!/usr/bin/env python3
"""
支持 CORS 的简单 HTTP 服务器
用于解决跨域访问问题
"""

import http.server
import socketserver
from http.server import SimpleHTTPRequestHandler
import sys
import os

class CORSRequestHandler(SimpleHTTPRequestHandler):
    def end_headers(self):
        self.send_header('Access-Control-Allow-Origin', '*')
        self.send_header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS')
        self.send_header('Access-Control-Allow-Headers', '*')
        super().end_headers()

    def do_OPTIONS(self):
        self.send_response(200, "ok")
        self.send_header('Access-Control-Allow-Origin', '*')
        self.send_header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS')
        self.send_header('Access-Control-Allow-Headers', '*')
        self.end_headers()

def run_server(port=8080):
    """启动支持 CORS 的 HTTP 服务器"""
    try:
        with socketserver.TCPServer(("", port), CORSRequestHandler) as httpd:
            print(f"🚀 启动支持 CORS 的 HTTP 服务器")
            print(f"📍 地址: http://localhost:{port}/")
            print(f"📁 目录: {os.getcwd()}")
            print(f"🔄 支持跨域访问 (CORS)")
            print(f"⏹️  按 Ctrl+C 停止服务器")
            httpd.serve_forever()
    except KeyboardInterrupt:
        print(f"\n⏹️  服务器已停止")
    except OSError as e:
        if e.errno == 98:  # Address already in use
            print(f"❌ 端口 {port} 已被占用")
            print(f"💡 请先停止现有服务器或使用其他端口")
        else:
            print(f"❌ 启动服务器失败: {e}")

if __name__ == "__main__":
    port = 8080
    if len(sys.argv) > 1:
        try:
            port = int(sys.argv[1])
        except ValueError:
            print("❌ 端口号必须是数字")
            sys.exit(1)
    
    run_server(port)